package com.xuanwu.ai.flow.service;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xuanwu.ai.core.domain.SessionInfo;
import com.xuanwu.ai.flow._enum.ErrorCodeEnum;
import com.xuanwu.ai.flow.dto.LoginRespDTO;
import com.xuanwu.ai.flow.mapper.TenantFlowAccountMapper;
import com.xuanwu.ai.flow.model.TenantFlowAccount;
import com.xuanwu.ai.flow.utils.JwtUtil;
import com.xuanwu.ai.web.exception.BizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Service
public class AuthServiceImpl {
    @Autowired
    private TenantFlowAccountMapper tenantFlowAccountMapper;

    @Value("${flow-tenant-account.token.expire.time:86400}")
    private Integer expireTime;

    public LoginRespDTO login(TenantFlowAccount tenantFlowAccount) {
        TenantFlowAccount account = tenantFlowAccountMapper.selectOne(Wrappers.<TenantFlowAccount>lambdaQuery()
                .eq(TenantFlowAccount::getFlowAccount, tenantFlowAccount.getFlowAccount())
                .eq(TenantFlowAccount::getFlowAccessKey, tenantFlowAccount.getFlowAccessKey())
                .eq(TenantFlowAccount::getStatus, 1)
                .last("limit 1"));
        if (ObjectUtils.isEmpty(account)) {
            throw new BizException(ErrorCodeEnum.TENANT_FLOW_ACCOUNT_NOT_EXIST);
        }

        SessionInfo sessionInfo = new SessionInfo();
        sessionInfo.setTenantId(account.getTenantId());
        sessionInfo.setUserId(Long.parseLong(account.getFlowAccount()));

        return buildLoginResp(account, sessionInfo);
    }

    /**
     * 获取token过期时间
     *
     * @return
     */
    private Date getAccessTokenExpires() {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.SECOND, expireTime);
        return c.getTime();
    }

    /**
     * 构造LoginRespDTO返回
     *
     * @return loginRespDTO
     */
    private LoginRespDTO buildLoginResp(TenantFlowAccount account, SessionInfo sessionInfo) {
        LoginRespDTO loginRespDTO = new LoginRespDTO();
        loginRespDTO.setTenantId(account.getTenantId());
        Date accessTokenExpires = getAccessTokenExpires();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        loginRespDTO.setToken(JwtUtil.wrap(sessionInfo, accessTokenExpires));
        loginRespDTO.setFlowAccount(account.getFlowAccount());
        loginRespDTO.setTokenExpiresAt(format.format(accessTokenExpires));
        loginRespDTO.setTenantName(account.getTenantName());

        return loginRespDTO;
    }
}
